import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';

export default class ChannelStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  total = 0;
  data = [];
  loading = false;
  company = [];
  prices = [];
  channelTypes = [];

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      this.data = yield api.search({ search, pg });
    } finally {
      this.loading = false;
    }
  }

  * get(id) {
    const res = yield api.get(id);
    return observable(res);
  }

  * update(channel) {
    yield api.update(channel);
    yield this.query();
  }

  * create(channel) {
    yield api.create(channel);
    yield this.query();
  }

  * remove(channel) {
    yield api.remove(channel.id);
    yield this.query();
  }

  * updateState(channel) {
    const { id, state } = channel;
    yield api.updateState({ id, state: !state });
    yield this.query();
  }

  * uploadRule(fileData) {
    yield api.uploadRule(fileData);
    yield this.query();
  }

  * getMerchant(fileData) {
    return yield api.getMerchantInfo(fileData);
  }

  * getDicts(id) {
    const types = yield api.getTopItems(id);
    const selectTypes = types.map((item) => ({
      label: item.name,
      value: item.itemId,
    }));
    this.channelTypes = selectTypes;
  }

  * channelPrice(id) {
    const price = yield api.getChanelPrice(id);
    price.forEach((item) => {
      // 解析 items 数组中每个对象的 description 属性为 JSON 对象
      item.items.forEach((itemObj) => {
        // eslint-disable-next-line no-param-reassign
        itemObj.description = JSON.parse(itemObj.description);
      });
    });
    const keyPrice = price.map((item, index) => ({
      ...item,
      key: String(index),
    }));
    this.prices = keyPrice;
  }

  * addProfitShare(args) {
    const { id, independentAccount } = args;
    const res = yield api.addProfitShare('CHANNEL', id, independentAccount.period || '1');
    const { imgUrl, mpAppId, baseUrl } = global.getEnvCfg();
    // 动态展示小程序链接
    const text = encodeURIComponent(`${imgUrl}/mp/?appId=${mpAppId}&sid=${res.sid}`);
    const url = `${baseUrl}/api/files/qrcode?text=${text}&height=300&width=300`;
    return url;
  }

  * getCompany(id) {
    const typeList = yield api.getCompany(id);
    const selectData = typeList.map((item) => {
      return ({
        label: item.name,
        value: item.id,
      });
    });
    this.company = selectData;
  }

  priceIdx(i, page, size) {
    return page * size + i + 1;
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get api() {
    return api;
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }
}
